package hu.ikti.oamadmin.beans.repository;

import java.io.Serializable;
import java.util.List;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;

import hu.ikti.oamadmin.beans.BaseBean;
import hu.ikti.oamadmin.types.entities.Repository;
import hu.ikti.oamadmin.ws.client.sync.SynchronisationManager;

@Name("editRepositoryBean")
@Scope(ScopeType.CONVERSATION)
public class EditRepositoryBean extends BaseBean implements Serializable {

	private static final long serialVersionUID = 1L;

	@In(create = true)
	@Out
	private Repository repository;

	@In
	private List<Repository> repositoryList;

	@Begin(pageflow = "editRepository", join = true)
	public String newRepository() {
		return "start";
	}

	@End
	public String saveRepository() {
		try {
			if (repository.getId() != null) {
				repository = (Repository) entityManager.find(Repository.class,
						repository.getId());
			} else {
				entityManager.persist(repository);
			}

			repository = entityManager.merge(repository);

			if (!repositoryList.contains(repository)) {
				repositoryList.add(repository);
			}

			FacesMessages.instance().add(Severity.INFO, "Saved repository: #0",
					repository.getUrl());

			return "done";
		} catch (Exception e) {
			e.printStackTrace();
			FacesMessages.instance().add(Severity.ERROR, "System error!");
			return null;
		}
	}

	@End
	public void cancel() {
		FacesMessages.instance().add(Severity.WARN, "Transaction canceled!");
	}

	public void synchronise(Long repoId) {
		repository = (Repository) entityManager.find(Repository.class, repoId);

		SynchronisationManager manager = new SynchronisationManager();
		manager.getSynchronisationManagerPort().synchronise(repository.getId());
	}
}
